package com.assignwork.service.impl;

import com.assignwork.dto.*;
import com.assignwork.entity.AssignWork;
import com.assignwork.entity.AssignWorkInfo;
import com.assignwork.entity.WorkArrangeShip;
import com.assignwork.mapper.WorkArrangeShipMapper;
import com.assignwork.service.*;
import com.assignwork.vo.*;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.common.cache.EsignCache;
import lombok.AllArgsConstructor;
import org.springblade.core.mp.base.BaseServiceImpl;
import org.springblade.core.secure.BladeUser;
import org.springblade.core.tool.utils.BeanUtil;
import org.springblade.core.tool.utils.Func;
import org.springblade.core.tool.utils.StringUtil;
import org.springblade.system.cache.DictBizCache;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @ClassName WorkArrangeShipServiceImpl
 * @Description 航运配工接口实现
 * @Author dujianyu
 * @Date 2023/12/21 15:49
 */
@Service
@AllArgsConstructor
public class WorkArrangeShipServiceImpl extends BaseServiceImpl<WorkArrangeShipMapper, WorkArrangeShip> implements IWorkArrangeShipService {

    private static final String ARRANGE_TYPE = "SHIP";
    private IWorkArrangeWorkersService workersService;
    private IWorkArrangeMachinesService machinesService;
    private IWorkArrangeShipCabinInfoService cabinInfoService;
    private IWorkArrangeShipUnderMachineService underMachineService;
    IAssignWorkService assignWorkService;

    @Override
    public boolean submitWaShip(WorkArrangeShipSubmitDTO dto) {
        WorkArrangeShip entity = BeanUtil.copy(dto, WorkArrangeShip.class);
        super.saveOrUpdate(entity);
        if (entity != null) {
            return workersService.submitWaWorkers(entity.getId(), dto.getWorkers(), ARRANGE_TYPE)
                    && machinesService.submitWaMachines(entity.getId(), dto.getMachines(), ARRANGE_TYPE)
                    && cabinInfoService.submitWaShipCabinInfo(entity.getId(), dto.getCabinInfos());
        }
        return true;
    }

    @Override
    public IPage<WorkArrangeShipPageVO> selectWaShipPage(WorkArrangeShipSearchDTO dto, IPage<WorkArrangeShipPageVO> page) {
        List<WorkArrangeShipPageVO> data = baseMapper.selectWaShipList(dto, page);
        return page.setRecords(dataProcess(data));
    }

    @Override
    public List<WorkArrangeShipPageVO> selectWaShipList(WorkArrangeShipSearchDTO dto) {
        List<WorkArrangeShipPageVO> data = baseMapper.selectWaShipList(dto, null);
        return dataProcess(data);
    }

    @Override
    public boolean removeWaShip(Long id) {
        return super.deleteLogic(Func.toLongList(id.toString()))
                && workersService.removeByArrangeId(id)
                && machinesService.removeByArrangeId(id)
                && cabinInfoService.removeByArrangeId(id)
                && underMachineService.removeByArrangeId(id);
    }

    @Override
    public List<WorkArrangeShipVO> listWorkArrangeShip(BladeUser bladeUser, AssignWorkDTO dto) {
        List<WorkArrangeShipVO> res = baseMapper.listWorkArrangeShip(dto);
        for (WorkArrangeShipVO re : res) {
            re.setLoadTypeName(DictBizCache.getValue(DailyPlanDTO.LOAD_TYPE, re.getLoadType()));
            re.setPackageBulkName(DictBizCache.getValue(DailyPlanDTO.PACKAGE_BULK, re.getPackageBulk()));
            for (WorkArrangeShipVO flowMachine : re.getFlowMachines()) {
                flowMachine.setFlowMachineName(DictBizCache.getValue("machine_kind", flowMachine.getFlowMachineKind()));
            }
            List<WorkArrangeShipVO> c = new ArrayList<>();
            for (WorkArrangeShipVO cabin : re.getCabins()) {
                cabin.setRealCabin1Name(DictBizCache.getValue(DailyPlanDTO.HOLD, cabin.getRealCabin1()));
                cabin.setRealCabin2Name(DictBizCache.getValue(DailyPlanDTO.HOLD, cabin.getRealCabin2()));
                cabin.setRealHatch1Name(DictBizCache.getValue(DailyPlanDTO.HOLD_POSITION, cabin.getRealHatch1()));
                cabin.setRealHatch2Name(DictBizCache.getValue(DailyPlanDTO.HOLD_POSITION, cabin.getRealHatch2()));
                cabin.setFixedMachinePositionName(DictBizCache.getValue("machine_position", cabin.getFixedMachinePosition()));

                c.add(cabin);
            }
            re.setCabins(c);
            List<WorkArrangeShipVO> under = new ArrayList<>();
            for (WorkArrangeShipVO underMachine : re.getUnderMachines()) {
                if (Func.isNotBlank(underMachine.getUnderMachineKind())) {
                    underMachine.setRealCabin1Name(DictBizCache.getValue(DailyPlanDTO.HOLD, underMachine.getRealCabin1()));
                    underMachine.setRealCabin2Name(DictBizCache.getValue(DailyPlanDTO.HOLD, underMachine.getRealCabin2()));
                    underMachine.setRealHatch1Name(DictBizCache.getValue(DailyPlanDTO.HOLD_POSITION, underMachine.getRealHatch1()));
                    underMachine.setRealHatch2Name(DictBizCache.getValue(DailyPlanDTO.HOLD_POSITION, underMachine.getRealHatch2()));
                    underMachine.setUnderMachineName(DictBizCache.getValue("machine_kind", underMachine.getUnderMachineKind()));
                    underMachine.setFixedMachinePositionName(DictBizCache.getValue("machine_position", underMachine.getFixedMachinePosition()));
                    under.add(underMachine);
                }
            }
            re.setUnderMachines(under);
        }

        return res;
    }

    @Override
    public PlanInfoVO getPlanInfo(WorkArrangeShipSearchDTO dto) {
        PlanInfoVO data = baseMapper.selectGetPlanInfo(dto);
        if (!Func.isNull(data.getAllHolds()) && !Func.isEmpty(data.getAllHolds())) {
            String[] holdList = data.getAllHolds().split(",");
            HashSet<String> holdSet = new HashSet<>();
            for (String s : holdList) {
                if (!Func.isEmpty(s)) {
                    holdSet.add(DictBizCache.getValue("hold", s));
                }
            }
            List<String> temp = new ArrayList<>(holdSet);
            Collections.sort(temp);
            data.setAllHolds(StringUtil.join(temp, ","));
        }
        return data;
    }

    @Override
    public Long getExistTeamId(WorkArrangeShipSearchDTO dto) {
        return baseMapper.selectOneExistTeamId(dto);
    }

    @Override
    public List<WorkArrangeShipMobileVO> listWorkArrange4Mobile(IPage page, LineAuditDTO dto) {
        List<WorkArrangeShipMobileVO> res = baseMapper.listWorkArrange4Mobile(page, dto);
        for (WorkArrangeShipMobileVO re : res) {
            re.setPackageBulkName(DictBizCache.getValue("package_bulk", re.getPackageBulk()));

            for (WorkArrangeShipUnderMachineVO vo : re.getUnderMachineList()) {
                vo.setMachineKindName(DictBizCache.getValue("machine_kind", vo.getMachineKind()));
            }

            for (StartedCabinVO vo : re.getPlanCabinList()) {
                vo.setCabinName(DictBizCache.getValue(DailyPlanDTO.HOLD, vo.getCabin()));
            }

            List<String> names = new ArrayList<>();
            for (WorkArrangeShipCabinInfoVO cabin : re.getCabinList()) {
                cabin.setRealCabin1Name(DictBizCache.getValue(DailyPlanDTO.HOLD, cabin.getRealCabin1()));
                cabin.setRealCabin2Name(DictBizCache.getValue(DailyPlanDTO.HOLD, cabin.getRealCabin2()));
                String[] vs = {cabin.getRealCabin1Name(), cabin.getRealCabin2Name()};
                names.add(Arrays.stream(vs).filter(i -> Func.isNotBlank(i)).collect(Collectors.joining(",")));
            }
            re.setCabinName(Func.join(names, "\\"));
        }
        return res;
    }

    @Override
    public WorkArrangeInfoVO arrangeInfoByArrangeId(Long arrangeId) {
        WorkArrangeInfoVO vo = baseMapper.arrangeInfoByArrangeId(arrangeId);
        if (vo == null) {
            return new WorkArrangeInfoVO();
        }
        vo.setSign(EsignCache.getSignByUserId(vo.getUpdateUser()));
        vo.setPackageBulkName(DictBizCache.getValue("package_bulk", vo.getPackageBulk()));
        vo.setShipBerthName(DictBizCache.getValue("berth", vo.getShipBerthKey()));
        vo.setTimeSpaceName(DictBizCache.getValue("time_space", vo.getTimeSpace()));
        vo.setSupportMachineKindName(DictBizCache.getValue("machine_kind", vo.getSupportMachineKind()));
        vo.setRealCabin1Name(DictBizCache.getValue("hold", vo.getRealCabin1()));
        vo.setRealHatch1Name(DictBizCache.getValue("hold_position", vo.getRealHatch1()));
        vo.setRealCabin2Name(DictBizCache.getValue("hold", vo.getRealCabin2()));
        vo.setRealHatch2Name(DictBizCache.getValue("hold_position", vo.getRealHatch2()));

        for (WorkArrangeUnderInfoVO underInfoVO : vo.getUnderInfo()) {
            underInfoVO.setMachineKindName(DictBizCache.getValue("machine_kind", underInfoVO.getMachineKind()));
        }

        List<AssignWorkVO> assignWorkVOS = assignWorkService.listAssignWorkByArrangeId(arrangeId);
        List<AssignWorkVO> collect = assignWorkVOS.stream().filter(AssignWorkVO::isLoader).collect(Collectors.toList());

        if (Func.isNotEmpty(collect)) {
            vo.setAssignWork(collect.get(0));
        }

        return vo;
    }


    private List<WorkArrangeShipPageVO> dataProcess(List<WorkArrangeShipPageVO> data) {
        for (WorkArrangeShipPageVO vo : data) {
            vo.setPackageBulkName(DictBizCache.getValue("package_bulk", vo.getPackageBulk()));
            List<String> realCabinNames = new ArrayList<>();
            List<String> planCabinNames = new ArrayList<>();
            List<String> supportNames = new ArrayList<>();
            List<String> fixedMachineNames = new ArrayList<>();
            List<String> underMachineNames = new ArrayList<>();
            vo.setPlanTon(new BigDecimal(0));
            vo.setShipMachine(0);
            for (WaShipCabinInfo info : vo.getCabinInfos()) {
                vo.setPlanTon(vo.getPlanTon().add(info.getPlanTon()).setScale(3, RoundingMode.HALF_UP));
                int count = vo.getShipMachine() + (Func.isNull(info.getShipMachineryCount()) ? 0 : info.getShipMachineryCount());
                vo.setShipMachine(count);
                List<String> real = new ArrayList<>();
                String c1 = !Func.isNull(info.getRealCabin1()) ? DictBizCache.getValue("hold", info.getRealCabin1()) : "";
                String h1 = !Func.isNull(info.getRealHatch1()) ? DictBizCache.getValue("hold_position", info.getRealHatch1()) : "";
                if (Func.isNull(c1)) {
                    real.add("");
                } else {
                    real.add(c1 + h1);
                }
                String c2 = !Func.isNull(info.getRealCabin2()) ? DictBizCache.getValue("hold", info.getRealCabin2()) : "";
                String h2 = !Func.isNull(info.getRealHatch2()) ? DictBizCache.getValue("hold_position", info.getRealHatch2()) : "";
                if (Func.isNull(c2)) {
                    real.add("");
                } else {
                    real.add(c2 + h2);
                }
                realCabinNames.add(StringUtil.join(real, " "));

                info.setFixedMachinePositionName(DictBizCache.getValue("machine_position", info.getFixedMachinePosition()));

                List<String> plan = new ArrayList<>();
                if (Func.isNoneBlank(info.getAllPlanCabins())) {
                    for (String s : info.getAllPlanCabins().split(",")) {
                        String cr = DictBizCache.getValue("hold", s.split(";")[0]) + DictBizCache.getValue("hold_position", s.split(";")[1]);
                        plan.add(cr);
                    }
                }
                planCabinNames.add(StringUtil.join(plan, ","));

                String supportMachineKindName = !Func.isNull(info.getSupportMachineKind()) && !Func.isEmpty(info.getSupportMachineKind()) ? DictBizCache.getValue("machine_kind", info.getSupportMachineKind()) : "无机械";
                supportNames.add(supportMachineKindName + (Func.isNull(info.getSupportMachineCorpName()) ? "无队组" : info.getSupportMachineCorpName()));

                fixedMachineNames.add(!Func.isNull(info.getFixedMachineName()) ? info.getFixedMachineName() : "无");

                if (!Func.isNull(info.getUnderMachines())) {
                    List<String> umList = new ArrayList<>();
                    for (String s : info.getUnderMachines().split(",")) {
                        String mk = DictBizCache.getValue("machine_kind", s.split("-")[0]);
                        String[] split = s.split("-");
                        if (split.length == 2) {
                            umList.add(mk + "-" + split[1]);
                        }
                        if (split.length == 3) {
                            umList.add(mk + "-" + split[1] + "-" + split[2]);
                        }

                    }
                    underMachineNames.add(StringUtil.join(umList, ","));
                }
            }
            vo.setPlanCabinsName(StringUtil.join(planCabinNames, "<br>"));
            vo.setRealCabinsName(StringUtil.join(realCabinNames, "<br>"));
            vo.setSupport(StringUtil.join(supportNames, "<br>"));
            vo.setFixedMachineName(StringUtil.join(fixedMachineNames, "<br>"));
            vo.setUnderMachinesNames(StringUtil.join(underMachineNames, "<br>"));
            vo.setGateCrane(vo.getCabinInfos().size());
        }
        return data;
    }
}
